package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //校验参数
        if (dto == null && StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPhone())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //对手机号和密码验证
        if (!StringUtils.isEmpty(dto.getPassword()) && !StringUtils.isEmpty(dto.getPhone())) {
            //登录
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = apUserMapper.selectOne(wrapper);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在!!");
            } else {
                String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                System.out.println("pwd = " + pwd);
                System.out.println(apUser.getPassword());
                if (pwd.equals(apUser.getPassword())) {
                    //登陆成功
                    Map<String, Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("user", apUser);
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    return ResponseResult.okResult(map);
                }else {
                    //密码输入错误
                    return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }

        }else {
            //3.设置登录
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
